package com.city.parking;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.gui.CommonDialog;

import com.baidu.lbsapi.auth.LBSAuthManagerListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapLongClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;
import com.baidu.navisdk.CommonParams.Const.ModelName;
import com.baidu.navisdk.CommonParams.NL_Net_Mode;
import com.baidu.navisdk.comapi.mapcontrol.BNMapController;
import com.baidu.navisdk.comapi.mapcontrol.MapParams.Const.LayerMode;
import com.baidu.navisdk.comapi.routeguide.RouteGuideParams.RGLocationMode;
import com.baidu.navisdk.comapi.routeplan.BNRoutePlaner;
import com.baidu.navisdk.comapi.routeplan.IRouteResultObserver;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams.NE_RoutePlan_Mode;
import com.baidu.navisdk.model.NaviDataEngine;
import com.baidu.navisdk.model.RoutePlanModel;
import com.baidu.navisdk.model.datastruct.RoutePlanNode;
import com.baidu.navisdk.ui.routeguide.BNavConfig;
import com.baidu.navisdk.ui.routeguide.BNavigator;
import com.baidu.navisdk.ui.widget.RoutePlanObserver;
import com.baidu.nplatform.comapi.basestruct.GeoPoint;
import com.city.parking.ParkingPopup.OnParkingClickListener;
import com.city.parking.util.HttpClientUtil;
import com.city.parking.util.HttpRequest;
import com.city.parking.util.HttpResult;
import com.city.parking.util.SharePrefUtil;
import com.city.parking.util.Utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BdMapFragment extends Fragment implements OnClickListener,
		OnMapStatusChangeListener, OnGetPoiSearchResultListener,
		OnCheckedChangeListener, OnGetRoutePlanResultListener, DrawerListener,
		OnParkingClickListener, OnMapClickListener {

	private MapView mMapView;
	private BaiduMap mBaiduMap;
	// 定位相关
	private LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private BitmapDescriptor mCurrentMarker;
	private Activity mActivity;
	private final int DEFAULT_ZOOM_LEVEL = 17;
	private float curZoomLevel = 0;

	private final int ORDER_PRICE = 1;
	private final int ORDER_IDLE = 2;
	private int mOrderType = ORDER_IDLE;
	private int mSearchArea = 1000;
	private int mSearchRetCnt = 0;
	private final int MAX_SEARCH_RET_CNT = 2;

	// UI相关
	private OnCheckedChangeListener radioButtonListener;
	private ImageButton requestLocButton, parkingTypeButton,
			parkingFilterButton, parkingFindButton, parkingRmbrButton;
	private ImageView navCenter;
	private boolean isFirstLoc = true;// 是否首次定位
	private boolean signParking = false;
	private PoiSearch mPoiSearch;
	private PoiNearbySearchOption mPoiSearchOption;
	private RoutePlanSearch mRoutePlan = null; // 搜索模块，也可去掉地图模块独立使用
	private int nodeIndex = -1;// 节点索引,供浏览节点时使用
	private RouteLine route = null;
	private OverlayManager routeOverlay = null;
	private Display mDisplay;
	private LinearLayout mRootView;
	private ParkingPopup mParkingPopup;
	private BitmapDescriptor mDestMarkBmp = BitmapDescriptorFactory
			.fromResource(R.drawable.dest_mark_loction);;
	private OverlayOptions mDestMark = null;
	private BitmapDescriptor mDestRmbrBmp = BitmapDescriptorFactory
			.fromResource(R.drawable.ico_car_location);
	private BitmapDescriptor mParkingBmp = BitmapDescriptorFactory
			.fromResource(R.drawable.ico_park);
	private ParkingOverlayManager mPom = null;
	private Point left = null;
	private Point right = null;
	private int ViewWidth = 0;

	private static BdMapFragment instance = null;
	private TextView makerTV = null;
	private TextView bigMakerTV = null;
	private int bigMakerTVHeight = 0;
	private Marker lastClickedPark = null;
	private BitmapDescriptor lastClickedParkBd = null;

	public static BdMapFragment getInstance() {
		return instance;
	}

	public static boolean instanced() {
		return instance != null;
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);

			// Log.d(TAG, "la="+locData.latitude+",lo="+locData.longitude);
			if (isFirstLoc) {
				isFirstLoc = false;
				moveToLocation(location, DEFAULT_ZOOM_LEVEL);
				ParkingApp.get().mCurCity = location.getCity();
				Utils.log("我的坐标：" + location.getCity());

				LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
				searchNearParks(ll);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	private void moveToLocation(BDLocation location, int zoom) {
		LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
		mBaiduMap.animateMapStatus(u);
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(zoom));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.map_frame, container, false);
		requestLocButton = (ImageButton) view.findViewById(R.id.locate_btn);
		requestLocButton.setOnClickListener(this);
		parkingTypeButton = (ImageButton) view
				.findViewById(R.id.parking_type_btn);
		parkingTypeButton.setOnClickListener(this);
		parkingRmbrButton = (ImageButton) view
				.findViewById(R.id.parking_rmbr_btn);
		parkingRmbrButton.setOnClickListener(this);
		parkingFilterButton = (ImageButton) view
				.findViewById(R.id.filter_parking_btn);
		//parkingFilterButton.setOnClickListener(this);
		parkingFilterButton.setVisibility(View.GONE);
		parkingFindButton = (ImageButton) view
				.findViewById(R.id.find_parking_btn);
		//parkingFindButton.setOnClickListener(this);
		parkingFindButton.setVisibility(View.GONE);
		navCenter = (ImageView) view.findViewById(R.id.nav_ico_center);
		navCenter.setOnClickListener(this);
		LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll_where_go);
		ll.setOnClickListener(this);
		View scan = view.findViewById(R.id.nav_ico_scanning);
		scan.setOnClickListener(this);

		if (signParking)
			parkingTypeButton.setImageResource(R.drawable.ico_all);
		else
			parkingTypeButton.setImageResource(R.drawable.ico_sign);

		// 地图初始化
		mMapView = (MapView) view.findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(17));
		mBaiduMap.setOnMapStatusChangeListener(this);
		mBaiduMap.setOnMapClickListener(this);

		mMapView.showZoomControls(false);
		mMapView.showScaleControl(false);

		// 定位初始化
		mLocClient = new LocationClient(this.getActivity());
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		option.setIsNeedAddress(true);
		mLocClient.setLocOption(option);
		mLocClient.start();

		mPoiSearch = PoiSearch.newInstance();
		mPoiSearch.setOnGetPoiSearchResultListener(this);

		mSearchArea = SharePrefUtil.getSearchRadius(1000);
		mPoiSearchOption = new PoiNearbySearchOption();
		mPoiSearchOption.radius(mSearchArea);
		mPoiSearchOption.pageCapacity(mSearchArea / 250 + 10);
		mPoiSearchOption.keyword("停车");

		mRoutePlan = RoutePlanSearch.newInstance();
		mRoutePlan.setOnGetRoutePlanResultListener(this);

		mDisplay = this.getActivity().getWindowManager().getDefaultDisplay();
		Point size = new Point();
		mDisplay.getSize(size);
		mRootView = (LinearLayout) view.findViewById(R.id.map_container);
		mActivity = this.getActivity();

		BaiduNaviManager.getInstance().initEngine(mActivity, getSdcardDir(),
				mNaviEngineInitListener, new LBSAuthManagerListener() {
					@Override
					public void onAuthResult(int status, String msg) {
						String str = null;
						if (0 == status) {
							str = "key校验成功!";
							Utils.log(str);
						} else {
							str = "key校验失败, " + msg;
							ParkingApp.showToast(str);
						}
					}
				});
		instance = this;

		mParkingPopup = new ParkingPopup(mActivity);
		mParkingPopup.setOnParkingClickListener(this);

		double last_lat = SharePrefUtil.getLastLatitude();
		double last_lng = SharePrefUtil.getLastLongitude();
		if (last_lat > 0 && last_lng > 0) {
			BDLocation location = new BDLocation();
			location.setLatitude(last_lat);
			location.setLongitude(last_lng);
			moveToLocation(location, DEFAULT_ZOOM_LEVEL);
		}

		mPom = new ParkingOverlayManager(mBaiduMap);
		mBaiduMap.setOnMarkerClickListener(mPom);
		//mBaiduMap.setOnMapLongClickListener(longMapClickListener);

		initMarkerView(inflater);
		return view;
	}
	
	private void initMarkerView(LayoutInflater inflater) {
		View mt = inflater.inflate(R.layout.maker_template, null);
		makerTV = (TextView) mt.findViewById(R.id.maker_content);
		makerTV.setBackgroundResource(R.drawable.ico_park_green);
		makerTV.setDrawingCacheEnabled(true);
		makerTV.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		makerTV.layout(0, 0, makerTV.getMeasuredWidth(),
				makerTV.getMeasuredHeight());
		
		View bmt = inflater.inflate(R.layout.big_maker_template, null);
		bigMakerTV = (TextView) bmt.findViewById(R.id.big_maker_content);
		bigMakerTV.setBackgroundResource(R.drawable.ico_park_green_big);
		bigMakerTV.setDrawingCacheEnabled(true);
		bigMakerTV.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		bigMakerTV.layout(0, 0, bigMakerTV.getMeasuredWidth(),
				bigMakerTV.getMeasuredHeight());
		bigMakerTVHeight = bigMakerTV.getMeasuredHeight();
	}

	private String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(
				Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}

	private boolean mIsEngineInitSuccess = false;
	private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {
		public void engineInitSuccess() {
			mIsEngineInitSuccess = true;
		}

		public void engineInitStart() {
		}

		public void engineInitFail() {
			Toast.makeText(mActivity, "engineInitFail", Toast.LENGTH_LONG)
					.show();
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		// activity 暂停时同时暂停地图控件
		mMapView.onPause();

		BDLocation location = mLocClient.getLastKnownLocation();
		if (location == null)
			return;
		SharePrefUtil.setLastLatitude((float) location.getLatitude());
		SharePrefUtil.setLastLongitude((float) location.getLongitude());
		ParkingApp.get().hideProgressBar();
	}

	@Override
	public void onResume() {
		super.onResume();
		// activity 恢复时同时恢复地图控件
		mMapView.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// activity 销毁时同时销毁地图控件
		mMapView.onDestroy();
		mPoiSearch.destroy();
		mLocClient.stop();
		instance = null;
	}

	private LatLng mSearchCenter;
	private void searchNearParks(LatLng center) {
		mSearchRetCnt = 0;
		mPom.clear();
		mSearchCenter = center;
		if (!signParking) {
			mPoiSearchOption.location(center);
			mPoiSearchOption.radius(mSearchArea);
			mPoiSearch.searchNearby(mPoiSearchOption);
		}
		getNearParkings(center, mSearchArea);

		ParkingApp.get().showProgressBar(mActivity);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.locate_btn:
			moveToLocation(mLocClient.getLastKnownLocation(), 17);
			break;
		case R.id.parking_type_btn:
			signParking = !signParking;
			if (signParking) {
				parkingTypeButton.setImageResource(R.drawable.ico_all);
				ParkingApp.showToast("只显示合作停车场");
			} else {
				parkingTypeButton.setImageResource(R.drawable.ico_sign);
			}
			searchNearParks(mBaiduMap.getMapStatus().target);
			break;
		case R.id.nav_ico_center:
			((MainActivity) mActivity).openSideMenu();
			break;
		case R.id.find_parking_btn:
			if (mPoiSearchOption == null) {
				Utils.log("mPoiSearchOption == null ?");
				return;
			}
			searchNearParks(mBaiduMap.getMapStatus().target);

			break;
		case R.id.filter_parking_btn:
			popupFilter();
			break;
		case R.id.ll_where_go:
			Intent i = new Intent(mActivity, SearchActivity.class);
			startActivityForResult(i, ParkingApp.RQST_CODE_SEARCH);

			break;
		case R.id.nav_ico_scanning:
			Intent i2 = new Intent(mActivity, ParkingScanActivity.class);
			startActivityForResult(i2, ParkingApp.RQST_CODE_SCAN);
			break;
		case R.id.parking_rmbr_btn:
			Intent i3 = new Intent(mActivity, MyParkingsActivity.class);
			startActivityForResult(i3, ParkingApp.RQST_CODE_FAVOR);
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode != Activity.RESULT_OK)
			return;
		if (requestCode == ParkingApp.RQST_CODE_SEARCH) {
			Bundle data = intent.getExtras();
			double lat = data.getDouble("lat");
			double lng = data.getDouble("lng");
			LatLng ll = new LatLng(lat, lng);
			mDestMark = new MarkerOptions().position(ll).icon(mDestMarkBmp)
					.zIndex(-1).draggable(true);
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			mBaiduMap.animateMapStatus(u);

			searchNearParks(ll);
		} else if (requestCode == ParkingApp.RQST_CODE_SCAN) {
			Bundle data = intent.getExtras();
			String result = data.getString("result");
			Utils.log("result = " + result);
			ParkingApp.showToast("result = " + result);
		} else if (requestCode == ParkingApp.RQST_CODE_FAVOR) {
			ParkingItem item = intent.getParcelableExtra("item");
			gotoRmbrParking(item.latitude, item.longitude, item.name, item.addr);
		} else if (requestCode == ParkingApp.RQST_CODE_REPORT) {
			String name = intent.getStringExtra("name");
			double lat = intent.getDoubleExtra("lat", -1);
			double lng = intent.getDoubleExtra("lng", -1);
			if (name == null || name.equals(""))
				name = "Unkown";
			LatLng ll = new LatLng(lat, lng);
			mDestMark = new MarkerOptions().position(ll).icon(mDestMarkBmp).zIndex(-1).title(name);
			mBaiduMap.addOverlay(mDestMark);
		}
	}

	private void gotoRmbrParking(double lat, double lng, String name, String addr) {
		mBaiduMap.clear();

		LatLng ll = new LatLng(lat, lng);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
		mBaiduMap.animateMapStatus(u);
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(DEFAULT_ZOOM_LEVEL));

		MarkerOptions mo = new MarkerOptions().position(ll).icon(mDestRmbrBmp);
		mBaiduMap.addOverlay(mo);

		return;
	}

	private void howToGo(PlanNode stNode, PlanNode edNode) {
		mRoutePlan.drivingSearch((new DrivingRoutePlanOption()).from(stNode)
				.to(edNode));
	}

	@Override
	public void onGetPoiDetailResult(PoiDetailResult result) {
		// TODO Auto-generated method stub
		if (result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(getActivity(), "抱歉，未找到结果", Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(getActivity(),
					result.getName() + ": " + result.getAddress(),
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onGetPoiResult(PoiResult result) {
		ParkingApp.get().hideProgressBar();
		// TODO Auto-generated method stub
		if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
			Utils.log("百度没有找到停车场，修改条件后再试试吧");
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			if (mSearchRetCnt++ == 0) {
				mBaiduMap.clear();
				if (mDestMark != null)
					mBaiduMap.addOverlay(mDestMark);
			}

			if (mDestMark != null)
				mBaiduMap.addOverlay(mDestMark);

			mPom.setResult(result);
			mPom.addToMap();

//			if (mSearchRetCnt >= MAX_SEARCH_RET_CNT && ViewWidth < mSearchArea*2)
//				mPom.zoomToSpan();
			
			lastClickedParkBd = null;
			lastClickedPark = null;
			return;
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

			// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
			String strInfo = "在";
			for (CityInfo cityInfo : result.getSuggestCityList()) {
				strInfo += cityInfo.city;
				strInfo += ",";
			}
			strInfo += "找到结果";
			Toast.makeText(getActivity(), strInfo, Toast.LENGTH_LONG).show();
		}
	}

	private class ParkingOverlayManager extends OverlayManager {
		private PoiResult result;
		private ArrayList<ParkingItem> ourParks;
		private final int BAIDU = 1;
		private final int NINEBIT = 2;
		private final int NINEBIT_SHIFT = 10000;
		private int type = 1;
		private boolean baiduAdded = false;
		private boolean OurAdded = false;
		private List<OverlayOptions> ops = new ArrayList<OverlayOptions>();
		
		public void clear() {
			ops.clear();
		}

		public void setResult(PoiResult result) {
			type = BAIDU;
			baiduAdded = false;
			this.result = result;
		}
		
		public void setResult2(ArrayList<ParkingItem> parks) {
			type = NINEBIT;
			OurAdded = false;
			this.ourParks = parks;
		}

		public ParkingOverlayManager(BaiduMap mBaiduMap) {
			super(mBaiduMap);
		}

		@Override
		public boolean onMarkerClick(Marker marker) {
			int idx = marker.getZIndex();
			Utils.log("click idx=" + idx);
			if (idx < 0) {
				if (marker.getTitle() != null && !marker.getTitle().equals("")) {
					Toast.makeText(mActivity, marker.getTitle(), Toast.LENGTH_SHORT).show();
				}
				return true;
			}

			ParkingItem park;
			BitmapDescriptor bd;
			if (idx < NINEBIT_SHIFT) {
				PoiInfo poi = result.getAllPoi().get(idx);
				park = new ParkingItem(poi);
				bd = BitmapDescriptorFactory.fromResource(R.drawable.ico_park_big);
			} else {
				park = ourParks.get(idx - NINEBIT_SHIFT);
				if (park.portLeftCount<10)
					bigMakerTV.setBackgroundResource(R.drawable.ico_park_red_big);
				else if (park.portLeftCount < 20)
					bigMakerTV.setBackgroundResource(R.drawable.ico_park_yellow_big);
				else
					bigMakerTV.setBackgroundResource(R.drawable.ico_park_green_big);

				if (park.portLeftCount > 999)
					bigMakerTV.setText("999");
				else
					bigMakerTV.setText("" + park.portLeftCount);
				bigMakerTV.buildDrawingCache();
				Bitmap b = Bitmap.createBitmap(bigMakerTV.getDrawingCache());
				bd = BitmapDescriptorFactory.fromBitmap(b);
			}
			
			if (lastClickedPark != null && lastClickedParkBd != null)
				lastClickedPark.setIcon(lastClickedParkBd);
			
			lastClickedParkBd = marker.getIcon();
			lastClickedPark = marker;
			marker.setIcon(bd);
			
			BDLocation bl = mLocClient.getLastKnownLocation();
			LatLng cl = new LatLng(bl.getLatitude(), bl.getLongitude());
			int distance = (int)DistanceUtil.getDistance(park.positionBD(), cl);
			mParkingPopup.bindPark(park, distance);
			InfoWindow iw = new InfoWindow(mParkingPopup.getView(), park.positionBD(), -bigMakerTVHeight);

			mBaiduMap.showInfoWindow(iw);
			return true;
		}

		@Override
		public List<OverlayOptions> getOverlayOptions() {
			Utils.log("getOverlayOptions type = " + type);
			if (type == BAIDU && !baiduAdded) {
				List<PoiInfo> pois = result.getAllPoi();
				for (int i = 0; i < pois.size(); i++) {
					MarkerOptions mo = new MarkerOptions();
					mo.position(pois.get(i).location);
					mo.icon(mParkingBmp);
					mo.zIndex(i); // must to be set
					ops.add(mo);
				}
				baiduAdded = true;
			} else if (type == NINEBIT && ourParks != null && !OurAdded) {
				int i = NINEBIT_SHIFT;
				for (ParkingItem park : ourParks) {
					double distance = DistanceUtil.getDistance(park.positionBD(), mSearchCenter);
					Utils.log(park.name + " = " + distance + "m");
					if (distance > mSearchArea || park.isDeleted == 1) {
						Utils.log("skip");
						continue;
					}

					MarkerOptions mo = new MarkerOptions();
					mo.position(park.positionBD());
					if (park.portLeftCount<10)
						makerTV.setBackgroundResource(R.drawable.ico_park_red);
					else if (park.portLeftCount < 20)
						makerTV.setBackgroundResource(R.drawable.ico_park_yellow);
					else
						makerTV.setBackgroundResource(R.drawable.ico_park_green);

					if (park.portLeftCount > 999)
						makerTV.setText("999");
					else
						makerTV.setText("" + park.portLeftCount);
					makerTV.buildDrawingCache();
					Bitmap b = Bitmap.createBitmap(makerTV.getDrawingCache());
					BitmapDescriptor bd = BitmapDescriptorFactory.fromBitmap(b);
					mo.icon(bd);
					mo.zIndex(i++);
					ops.add(mo);
				}
				OurAdded = true;
			}

			return ops;
		}
	}

	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult result) {
		// TODO Auto-generated method stub
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(getActivity(), "抱歉，未找到结果", Toast.LENGTH_SHORT)
					.show();
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
			// 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
			// result.getSuggestAddrInfo()
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			nodeIndex = -1;
			route = result.getRouteLines().get(0);
			DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
			// mBaiduMap.setOnMarkerClickListener(overlay);

			routeOverlay = overlay;
			overlay.setData(result.getRouteLines().get(0));
			overlay.addToMap();
			overlay.zoomToSpan();
		}
	}

	// 定制RouteOverly
	private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

		public MyDrivingRouteOverlay(BaiduMap baiduMap) {
			super(baiduMap);
		}

		@Override
		public BitmapDescriptor getStartMarker() {
			return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
		}

		@Override
		public BitmapDescriptor getTerminalMarker() {
			return BitmapDescriptorFactory.fromResource(R.drawable.icon_ed);
		}
	}

	@Override
	public void onGetTransitRouteResult(TransitRouteResult arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult arg0) {
		// TODO Auto-generated method stub

	}

	private PopupWindow mFilterPw;
	private View mPopupFilterView;

	private void popupFilter() {
		// use popup window to replace info window
		if (mPopupFilterView == null) {
			LayoutInflater li = LayoutInflater.from(this.getActivity());
			mPopupFilterView = li.inflate(R.layout.filter_popup, null);
			mPopupFilterView.measure(0, 0);

			RadioGroup orderType = (RadioGroup) mPopupFilterView
					.findViewById(R.id.order_type);
			RadioGroup searchArea = (RadioGroup) mPopupFilterView
					.findViewById(R.id.search_area);
			orderType.setOnCheckedChangeListener(this);
			searchArea.setOnCheckedChangeListener(this);
			int check_rb;
			switch (mSearchArea) {
			case 5000:
				check_rb = R.id.area_5km;
				break;
			case 500:
				check_rb = R.id.area_500m;
				break;
			case 250:
				check_rb = R.id.area_250m;
				break;
			default:
				check_rb = R.id.area_1km;
				break;
			}
			RadioButton rb = (RadioButton) mPopupFilterView
					.findViewById(check_rb);
			rb.setChecked(true);
		}

		if (mFilterPw == null) {
			mFilterPw = new PopupWindow(mPopupFilterView);
			mFilterPw.setWidth(LayoutParams.WRAP_CONTENT); // auto adjust
			mFilterPw.setHeight(LayoutParams.WRAP_CONTENT);
			mFilterPw.setFocusable(true);
			mFilterPw.setOutsideTouchable(true);
			mFilterPw.setBackgroundDrawable(new BitmapDrawable());
			mFilterPw.setClippingEnabled(false);
		}
		int x = parkingFilterButton.getWidth()
				- mPopupFilterView.getMeasuredWidth();
		int y = -parkingFilterButton.getHeight()
				- mPopupFilterView.getMeasuredHeight();

		mFilterPw.showAsDropDown(parkingFilterButton, x, y);
	}

	@Override
	public void onMapStatusChange(MapStatus status) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onMapStatusChangeFinish(MapStatus status) {
		// TODO Auto-generated method stub
		Utils.log("onMapStatusChangeFinish center="+status.target+",radius="+mSearchArea);
		double distance = DistanceUtil.getDistance(status.target, mSearchCenter);
		if (distance > mSearchArea/2)
			searchNearParks(status.target);
		else
			Utils.log("distance <= MIN_RESEACH_DISTANCE");

		if (curZoomLevel != status.zoom) {
			curZoomLevel = status.zoom;			
			if (left == null)
				left = new Point(0, mMapView.getHeight());
			if (right == null)
				right = new Point(mMapView.getWidth(), mMapView.getHeight());
			LatLng latlng1 = mBaiduMap.getProjection().fromScreenLocation(left);
			LatLng latlng2 = mBaiduMap.getProjection().fromScreenLocation(right);
			ViewWidth = (int) DistanceUtil.getDistance(latlng1, latlng2);
			
			if (ViewWidth <= 1000)
				mSearchArea = 500;
			else if (ViewWidth < 2000)
				mSearchArea = 1000;
			else
				mSearchArea = 2500;
			
			Utils.log("zoom level changed, ViewWidth="+ViewWidth+",mSearchArea="+mSearchArea);
		}
	}

	@Override
	public void onMapStatusChangeStart(MapStatus arg0) {
		// TODO Auto-generated method stub
		Utils.log("onMapStatusChangeStart");
	}

	private void startCalcRoute(ParkingItem park) {
		// 获取输入的起终点
		BDLocation loc = mLocClient.getLastKnownLocation();

		// 起点
		RoutePlanNode startNode = new RoutePlanNode(
				(int) (loc.getLatitude() * 1e5),
				(int) (loc.getLongitude() * 1e5), RoutePlanNode.FROM_MAP_POINT,
				loc.getAddrStr(), loc.getDistrict());
		// 终点
		RoutePlanNode endNode = new RoutePlanNode(
				(int) (park.latitude * 1e5), (int) (park.longitude * 1e5),
				RoutePlanNode.FROM_MAP_POINT, park.addr, park.name);
		// 将起终点添加到nodeList
		ArrayList<RoutePlanNode> nodeList = new ArrayList<RoutePlanNode>(2);
		nodeList.add(startNode);
		nodeList.add(endNode);
		BNRoutePlaner.getInstance().setObserver(
				new RoutePlanObserver(mActivity, null));
		// 设置算路方式
		BNRoutePlaner.getInstance().setCalcMode(
				NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME);
		// 设置算路结果回调
		BNRoutePlaner.getInstance()
				.setRouteResultObserver(mRouteResultObserver);
		// 设置起终点并算路
		boolean ret = BNRoutePlaner.getInstance().setPointsToCalcRoute(
				nodeList, NL_Net_Mode.NL_Net_Mode_OnLine);
		if (!ret) {
			Toast.makeText(mActivity, "规划失败", Toast.LENGTH_SHORT).show();
		}
	}

	private RoutePlanModel mRoutePlanModel = null;

	private void startNavi(boolean isReal) {
		if (mRoutePlanModel == null) {
			Toast.makeText(mActivity, "请先算路！", Toast.LENGTH_LONG).show();
			return;
		}
		// 获取路线规划结果起点
		RoutePlanNode startNode = mRoutePlanModel.getStartNode();
		// 获取路线规划结果终点
		RoutePlanNode endNode = mRoutePlanModel.getEndNode();
		if (null == startNode || null == endNode) {
			return;
		}
		// 获取路线规划算路模式
		int calcMode = BNRoutePlaner.getInstance().getCalcMode();
		Bundle bundle = new Bundle();
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_VIEW_MODE,
				BNavigator.CONFIG_VIEW_MODE_INFLATE_MAP);
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_CALCROUTE_DONE,
				BNavigator.CONFIG_CLACROUTE_DONE);
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_START_X,
				startNode.getLongitudeE6());
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_START_Y,
				startNode.getLatitudeE6());
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_END_X, endNode.getLongitudeE6());
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_END_Y, endNode.getLatitudeE6());
		bundle.putString(BNavConfig.KEY_ROUTEGUIDE_START_NAME,
				mRoutePlanModel.getStartName(mActivity, false));
		bundle.putString(BNavConfig.KEY_ROUTEGUIDE_END_NAME,
				mRoutePlanModel.getEndName(mActivity, false));
		bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_CALCROUTE_MODE, calcMode);
		if (!isReal) {
			// 模拟导航
			bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_LOCATE_MODE,
					RGLocationMode.NE_Locate_Mode_RouteDemoGPS);
		} else {
			// GPS 导航
			bundle.putInt(BNavConfig.KEY_ROUTEGUIDE_LOCATE_MODE,
					RGLocationMode.NE_Locate_Mode_GPS);
		}

		Intent intent = new Intent(mActivity, BNavigatorActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	private IRouteResultObserver mRouteResultObserver = new IRouteResultObserver() {

		@Override
		public void onRoutePlanYawingSuccess() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onRoutePlanYawingFail() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onRoutePlanSuccess() {
			// TODO Auto-generated method stub
			BNMapController.getInstance().setLayerMode(
					LayerMode.MAP_LAYER_MODE_ROUTE_DETAIL);
			mRoutePlanModel = (RoutePlanModel) NaviDataEngine.getInstance()
					.getModel(ModelName.ROUTE_PLAN);

			DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
			// mBaiduMap.setOnMarkerClickListener(overlay);

			// routeOverlay = overlay;mRoutePlanModel.getr
			// overlay.setData(mRoutePlanModel.);
			overlay.addToMap();
			overlay.zoomToSpan();
			startNavi(true);
		}

		@Override
		public void onRoutePlanFail() {
			// TODO Auto-generated method stub
		}

		@Override
		public void onRoutePlanCanceled() {
			// TODO Auto-generated method stub
		}

		@Override
		public void onRoutePlanStart() {
			// TODO Auto-generated method stub

		}

	};

	@Override
	public void onDrawerClosed(View arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDrawerOpened(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDrawerSlide(View arg0, float arg1) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDrawerStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onParkingClick(ParkingItem park) {
		// TODO Auto-generated method stub

		startCalcRoute(park);
	}

	@Override
	public void onParkingDescClick(ParkingItem park) {
		// TODO Auto-generated method stub
		Intent i = new Intent(mActivity, ParkingDetailActivity.class);
		i.putExtra("park", park);
		startActivity(i);
	}

	@Override
	public void onCheckedChanged(RadioGroup grp, int idx) {
		// TODO Auto-generated method stub
		if (mFilterPw == null)
			return;

		switch (idx) {
		case R.id.order_idle:
			mOrderType = ORDER_IDLE;
			break;
		case R.id.order_price:
			mOrderType = ORDER_PRICE;
			break;
		case R.id.area_5km:
			mSearchArea = 5000;
			break;
		case R.id.area_1km:
			mSearchArea = 1000;
			break;
		case R.id.area_500m:
			mSearchArea = 500;
			break;
		case R.id.area_250m:
			mSearchArea = 250;
			break;
		}

		SharePrefUtil.setSearchRadius(mSearchArea);

		mFilterPw.dismiss();
	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub
		mBaiduMap.hideInfoWindow();
	}

	@Override
	public boolean onMapPoiClick(MapPoi arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	private final int NEAR_PARK = 1;

	private void getNearParkings(LatLng ll, int radius) {
		JSONObject json = new JSONObject();
		try {
			json.put("longitude", ll.longitude);
			json.put("latitude", ll.latitude);
			json.put("radius", radius);
		} catch (JSONException e1) {
			e1.printStackTrace();
			return;
		}
		HttpRequest req = new HttpRequest(ParkingApp.url_get_near_park, NEAR_PARK, json.toString(), handler);
		HttpClientUtil.post(req);
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			ParkingApp.get().hideProgressBar();
			if (msg.arg1 == HttpRequest.NET_SUCCESS) {
				HttpResult ret = (HttpResult) msg.obj;
				if (ret != null && ret.status == HttpResult.STATUS_SUCCESS) {
					ArrayList<ParkingItem> parks = ParkingItem.fromJsonArray(ret.body);

					if (mSearchRetCnt++ == 0) {
						mBaiduMap.clear();
						if (mDestMark != null)
							mBaiduMap.addOverlay(mDestMark);
					}

					mPom.setResult2(parks);
					mPom.addToMap();
//					if ((mSearchRetCnt >= MAX_SEARCH_RET_CNT || signParking) && ViewWidth < mSearchArea*2) {
//						mPom.zoomToSpan();
//					}
					return;
				}
			}
			Utils.log("九比特服务器异常");
		}
	};

	private OnMapLongClickListener longMapClickListener = new OnMapLongClickListener() {  
	    /** 
	    * 地图长按事件监听回调函数 
	    * @param point 长按的地理坐标 
	    */  
	    public void onMapLongClick(LatLng point){
			Intent i = new Intent(mActivity, ReportLocationActivity.class);
	        Bundle bundle = new Bundle();				//创建Bundle对象
	        bundle.putDouble("lat", point.latitude);	//装入数据
	        bundle.putDouble("lng", point.longitude);	//装入数据
	        i.putExtras(bundle);
			startActivityForResult(i, ParkingApp.RQST_CODE_REPORT);
	    }  
	};
}
